<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @open="onOpen" @close="onClose">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="onSave">确定</el-button>
        <el-button size="small" @click="$emit('input',false)">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleData } from '@/api/role.js'
import { getUserInfoById, updateUserAssignRoles } from '@/api/user.js'
export default {
  model: {
    prop: 'showRoleDialog'
  },
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roles: [],
      // 选中的选项的id
      checkList: []
    }
  },
  created() {},
  methods: {
    // 获取所有角色列表
    async loadRoleList() {
      const res = await getRoleData()
      // console.log(res)
      this.roles = res.rows
    },
    // 获取员工基本信息(角色)
    async getUserDetailById() {
      const { roleIds } = await getUserInfoById(this.userId)
      // console.log(roleIds)
      this.checkList = roleIds // 赋值本用户的角色
    },
    // Dialog 打开的回调
    onOpen() {
      this.loadRoleList()
      this.getUserDetailById()
    },
    // Dialog 关闭的回调、
    onClose() {
      this.$emit('input', false)
      this.checkList = []
    },
    // 确定按钮
    async onSave() {
      if (this.checkList.length === 0) {
        return this.$message.error('请选择一个角色')
      }
      await updateUserAssignRoles(this.userId, this.checkList)
      this.$message.success('分配角色成功')
      this.$emit('input', false)
    }
  }
}
</script>
